package com.realgodo.site.service;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.hibernate.DefaultEntityManager;

import com.realgodo.site.entity.security.User;
import com.realgodo.site.entity.vocation.UserVocation;
import com.realgodo.site.entity.vocation.Vocation;

/**
 * @author bijiqiang E-mail: bijiqiang@gmail.com
 * @version 创建时间：2009-12-13上午09:30:47
 * @since jdk1.5
 * @version 0.1
 */
@Service("vocationManager")
@Transactional
public class VocationManager extends DefaultEntityManager<Vocation, Long> {
	@Autowired
	protected SessionFactory sessionFactory;

	public void saveUserVocation(User user, Long[] vocationIds) {
		Session session = sessionFactory.getCurrentSession();
		Query hql = session
				.createQuery("delete from  UserVocation o where o.user.id = ?");
		hql.setParameter(0, user.getId());
		hql.executeUpdate();
		UserVocation userVocation;
		Vocation vocation;
		for (Long id : vocationIds) {
			userVocation = new UserVocation();
			userVocation.setUser(user);
			vocation = entityDao.get(id);
			userVocation.setVocation(vocation);
			session.save(userVocation);
		}
	}

	@SuppressWarnings("unchecked")
	public List<Vocation> getMyVocation(User user) {
		Session session = sessionFactory.getCurrentSession();
		Query hql = session
				.createQuery("select o.vocation from  UserVocation o where o.user.id = ?");
		hql.setParameter(0, user.getId());
		return hql.list();
	}

	public Long getUserCountInVocatin(Long vocationId) {

		Session session = sessionFactory.getCurrentSession();
		Query hql = session
				.createQuery("select count(o.user.id) from  UserVocation o where o.vocation.id = ?");
		hql.setParameter(0, vocationId);
		return (Long) hql.uniqueResult();
	}

	public Long getUserCountInTopVocatin(Long vocationId) {

		Session session = sessionFactory.getCurrentSession();
		Query hql = session
				.createQuery("select count(o.user.id) from  UserVocation o where o.vocation.parent.id = ?");
		hql.setParameter(0, vocationId);
		return (Long) hql.uniqueResult();
	}

	public List<Vocation> getAllVocations() {
		List<Vocation> vocations = this.getAll();
		for (Vocation vocation : vocations) {
			if (null == vocation.getParent()) {
				vocation.setCount(this.getUserCountInTopVocatin(vocation
						.getId()));
			} else {
				vocation.setCount(this.getUserCountInVocatin(vocation.getId()));
			}

		}
		return vocations;
	}
}
